package thin4ca

import scala.collection.mutable.Stack

class TemplateAnalyzer(val domain: Domain) {

  def runOn(tf: TemplateFactory) {

    tf.listTemplates.foreach(file => {

      val definitions = tf.read(file).analyze
      println("runOn " + definitions)

      var rootContext = new DefContext("")
      val contextStack = new Stack[DefContext]();
      contextStack.push(rootContext);
      
      val er = new EntityDefResolver
      definitions.foreach(d => {
        println("processing: " + d + " in " + contextStack)
        d match {
          case "LIST" => { 
            contextStack.push(new DefContext(entityNameFrom(file)))
          }
          case "LIST.end" => { 
            println("Fine list")
            contextStack.pop
          }
          case _ => er.addDefinition( d, contextStack.top )
        }
      })
      val entitiesDef = er.resolveEntities
      println("entitiesDef: " + entitiesDef)
      domain.updateEntities(entitiesDef)
    })
  }
  
  def entityNameFrom(fileName: String) : String = fileName.takeWhile( ! _.equals('.')).mkString
}
